package com.meshnetics.gb.stack.mac.io;

import com.meshnetics.gb.util.ToStringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Sergey Klimenko (sklimenko@meshnetics.com)
 */
public class LoggerInputStream extends InputStream {
    private final InputStream inputStream;
    private final String port;

    private static final Log log = LogFactory.getLog(LoggerInputStream.class);

    public LoggerInputStream(InputStream inputStream, String port) {
        this.inputStream = inputStream;
        this.port = port;
    }

    public int read() throws IOException {
        int b = inputStream.read();
        if (log.isDebugEnabled()) {
            if (b == -1) {
                log.debug("byte read from port: EOF");
            } else {
                String hex = Integer.toHexString(b);
                log.debug("byte read from port " + port + ": " + (hex.length() == 1 ? ("0x0" + hex) : ("0x" + hex)));
            }
        }
        return b;
    }

    public int read(byte b[], int off, int len) throws IOException {
        int i = inputStream.read(b, off, len);
        if (log.isDebugEnabled()) {
            log.debug("bytes read from port " + port + ": " + ToStringUtil.toString(b, off, i));
        }
        return i;
    }

    public long skip(long n) throws IOException {
        return inputStream.skip(n);
    }

    public int available() throws IOException {
        return inputStream.available();
    }

    public void close() throws IOException {
        inputStream.close();
    }

    public synchronized void mark(int readlimit) {
        inputStream.mark(readlimit);
    }

    public synchronized void reset() throws IOException {
        inputStream.reset();
    }
}
